package cn.edu.ljl.rest;

import cn.edu.ljl.DBMS;
import cn.edu.ljl.Student;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;
import java.sql.SQLException;
import java.util.List;

public class StudentRefer  extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        this.doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String page = request.getParameter("page");

        int offset = (Integer.valueOf(page).intValue() - 1) * 2;

        String sql = "SELECT * FROM grade ORDER BY id DESC LIMIT 2 OFFSET " + offset;

        System.out.println(sql);

        try {
            List<Student> students = DBMS.getStudents(sql);

            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            try(Writer writer = response.getWriter()) {
                writer.write(this.toJson(students));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private String toJson(List<Student> students) {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        sb.append("\"students\": [");

        for(int i=0; i<students.size(); i++) {
            Student student = students.get(i);
            if (i > 0) sb.append(",");
            sb.append(String.format(
                    "{\"ID\": \"%s\", \"number\": \"%s\",\"name\": \"%s\",\"subject\": \"%s\",\"score\":" +
                            " \"%s\",\"feel\": \"%s\"}",
                    student.getID(),student.getNumber() ,student.getName(), student.getSubject(),
                    student.getScore(), student.getFeel()
            ));
        }

        sb.append("]");
        sb.append("}");
        System.out.println(sb);
        return sb.toString();
    }
}



//{"students":
// [
// {"ID": "30", "number": "21","name": "李俊霖","subject": "线性代数I","score": "92","feel": "复习要多复习作业题目"}
// ,
// {"ID": "29", "number": "21","name": "李俊霖","subject": "思修","score": "82","feel": "应该多看看书"}
// ]}








